#!/bin/bash

# 确保脚本在出错时退出
set -e

# 设置颜色
green='\033[0;32m'
red='\033[0;31m'
blue='\033[0;34m'
reset='\033[0m'

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
BACKEND_DIR="$PROJECT_ROOT/workflow-engine-backend"
FRONTEND_DIR="$PROJECT_ROOT/workflow-engine-frontend"

# 帮助信息
show_help() {
    echo -e "${blue}工作流引擎系统启动脚本${reset}"
    echo "用法: ./start.sh [选项]"
    echo "选项:"
    echo "  --backend       仅构建和启动后端服务"
    echo "  --frontend      仅构建和启动前端服务"
    echo "  --build-only    仅构建项目，不启动服务"
    echo "  --help          显示帮助信息"
    echo "  无参数         构建并启动前后端服务"
}

# 构建后端
build_backend() {
    echo -e "${blue}正在构建后端项目...${reset}"
    cd "$BACKEND_DIR"
    mvn clean install -DskipTests
    echo -e "${green}后端构建成功${reset}"
}

# 启动后端
start_backend() {
    echo -e "${blue}正在启动后端服务...${reset}"
    cd "$BACKEND_DIR"
    mvn spring-boot:run &
    BACKEND_PID=$!
    echo -e "${green}后端服务已启动，PID: $BACKEND_PID${reset}"
    echo -e "${green}后端服务地址: http://localhost:8080/api${reset}"
    echo -e "${green}H2控制台地址: http://localhost:8080/api/h2-console${reset}"
}

# 构建前端
build_frontend() {
    echo -e "${blue}正在构建前端项目...${reset}"
    cd "$FRONTEND_DIR"
    npm install
    npm run build
    echo -e "${green}前端构建成功${reset}"
}

# 启动前端
start_frontend() {
    echo -e "${blue}正在启动前端服务...${reset}"
    cd "$FRONTEND_DIR"
    npm run dev &
    FRONTEND_PID=$!
    echo -e "${green}前端服务已启动，PID: $FRONTEND_PID${reset}"
    echo -e "${green}前端服务地址: http://localhost:3000${reset}"
}

# 清理资源
cleanup() {
    echo -e "${blue}正在停止服务...${reset}"
    if [ -n "$BACKEND_PID" ]; then
        kill $BACKEND_PID 2>/dev/null || true
    fi
    if [ -n "$FRONTEND_PID" ]; then
        kill $FRONTEND_PID 2>/dev/null || true
    fi
    echo -e "${green}服务已停止${reset}"
}

# 注册清理函数
trap cleanup EXIT

# 解析命令行参数
case "$1" in
    --help)        show_help; exit 0 ;;
    --backend)     build_backend; start_backend; ;; 
    --frontend)    build_frontend; start_frontend; ;; 
    --build-only)  build_backend; build_frontend; echo -e "${green}构建完成，服务未启动${reset}"; exit 0; ;;
    "")            build_backend; build_frontend; start_backend; start_frontend; ;;
    *)             echo -e "${red}未知选项: $1${reset}"; show_help; exit 1; ;;
esac

# 等待服务启动
echo -e "${blue}服务正在启动中...${reset}"
sleep 5

echo -e "${green}所有服务已启动完成！${reset}"
echo -e "${green}后端服务地址: http://localhost:8080/api${reset}"
echo -e "${green}前端服务地址: http://localhost:3000${reset}"
echo -e "${blue}按 Ctrl+C 停止所有服务${reset}"

# 保持脚本运行
wait